import requests
import asyncio
from playwright.async_api import async_playwright

async def main():
    # 1. 获取登录凭证
    login_url = "https://xuntian-cloud-test3.tclpv.com/api/auth/login"
    payload = {
        "username": "kt_wuzex",
        "password": "tcl123",
        "type": 1,
        "from": "xts-new"
    }
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
    }
    
    resp = requests.post(login_url, json=payload, headers=headers)
    data = resp.json()
    print("✅ 登录响应:", data)

    async with async_playwright() as p:
        # 2. 启动浏览器并创建上下文
        browser = await p.chromium.launch(
            headless=False,
            args=[
                "--disable-web-security",
                "--disable-site-isolation-trials",
                "--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure"
            ]
        )
        
        context = await browser.new_context(
            ignore_https_errors=True,
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
            # 关键设置：确保Cookie作用域正确
            base_url="https://xuntian-cloud-test3.tclpv.com/"
        )
        
        # 3. 创建页面实例
        page = await context.new_page()

        token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJrdF93dXpleCIsImF2YXRhclVybCI6bnVsbCwiYWNjb3VudFR5cGUiOm51bGwsInVzZXJOYW1lIjoia3Rfd3V6ZXgiLCJ1c2VySWQiOiIxMTExMDAiLCJlbmFibGVkIjp0cnVlLCJyZWFsTmFtZSI6Iui2hee6p-euoeeQhuWRmCIsIkNPREUiOiIxIiwidXNlckRhdGFBcmVhIjoiMjAxOTA4MDgiLCJjbGllbnREZXZpY2VJZCI6InBjXzQ0NDE5ZjBiYTEwYzRmYzE5NmJkMGQyNmNjODJmNWM5IiwiYWRtaW5TdGF0ZSI6dHJ1ZSwiZXhwIjoxNzUzMzg3NTMyLCJpYXQiOjE3NTA3NTk1MzIsImVtYWlsIjoiIiwianRpIjoicGNfNDQ0MTlmMGJhMTBjNGZjMTk2YmQwZDI2Y2M4MmY1YzkifQ.d_4KGJ_QwF0bxSA0ETNHdgZchnjwlfGfk6keXpx3l8SmpP5ShheJ0vqi96qA8MlIeRdup6_oXZrh5XdTbRpvpA'
        refreshToken = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJrdF93dXpleCIsImF2YXRhclVybCI6bnVsbCwiYWNjb3VudFR5cGUiOm51bGwsInVzZXJOYW1lIjoia3Rfd3V6ZXgiLCJ1c2VySWQiOiIxMTExMDAiLCJlbmFibGVkIjp0cnVlLCJyZWFsTmFtZSI6Iui2hee6p-euoeeQhuWRmCIsIkNPREUiOiIxIiwidXNlckRhdGFBcmVhIjoiMjAxOTA4MDgiLCJjbGllbnREZXZpY2VJZCI6InBjXzQ0NDE5ZjBiYTEwYzRmYzE5NmJkMGQyNmNjODJmNWM5IiwiYWRtaW5TdGF0ZSI6dHJ1ZSwiZXhwIjoxNzUzMzg3NTMyLCJpYXQiOjE3NTA3NTk1MzIsImVtYWlsIjoiIiwianRpIjoicGNfNDQ0MTlmMGJhMTBjNGZjMTk2YmQwZDI2Y2M4MmY1YzkifQ.d_4KGJ_QwF0bxSA0ETNHdgZchnjwlfGfk6keXpx3l8SmpP5ShheJ0vqi96qA8MlIeRdup6_oXZrh5XdTbRpvpA'
        data01 = {"token01":token}
        # 设置带有 Authorization 的请求头
        await page.set_extra_http_headers({
            "Authorization": f"Bearer {data01['token01']}"
        })
        
        # 4. 先导航到域名下的空白页建立上下文
        await page.goto("https://xuntian-cloud-test3.tclpv.com/", wait_until="domcontentloaded")
        
        admin_refresh_token = 'IfU5abMzknQqTgoLz64Ck2oD2R5oC6lebGVwtQhtiF4t6ctBVkNfBmhD4lqZAiZebvLSWAf9oKvpoFY7GIAbE-yIBgeVr0P0TCEARgSDHhE52t8l_vJLZwYptMbdqdru'
        admin_token = 'm-MRYZyURX2kZ5mYLGORXAho7t6yKg5IZEKd5aoqN2bPcoGgWqLhDewEaCp7LH5xdeqX0szxMIRf1-ExnKtFZaErShGs6p6FuxrPCM8UbVGib1spJNeMpe6vRAH8eRX2'
        # 5. 设置Cookie（根据实际抓取的Cookie调整）
        cookies = [
            {
                "name": "__userId__",
                "value": str(data["userId"]),
                "domain": "xuntian-cloud-test3.tclpv.com",
                "path": "/",
                "secure": False,
                "sameSite": "Lax",
                "httpOnly": False
            },
            {
                "name": "token",
                "value": token,
                "domain": "xuntian-cloud-test3.tclpv.com",
                "path": "/",
                "secure": False,
                "sameSite": "Lax",
                "httpOnly": False
            },
            {
                "name": "refreshToken",
                "value": refreshToken,
                "domain": "xuntian-cloud-test3.tclpv.com",
                "path": "/",
                "secure": False,
                "sameSite": "Lax",
                "httpOnly": False
            },
            {
                "name": "admin_token",
                "value": admin_token,
                "domain": "xuntian-cloud-test3.tclpv.com",
                "path": "/",
                "secure": False,
                "sameSite": "Lax",
                "httpOnly": False
            },
            {
                "name": "admin_refresh_token",
                "value": admin_refresh_token,
                "domain": "xuntian-cloud-test3.tclpv.com",
                "path": "/",
                "secure": False,
                "sameSite": "Lax",
                "httpOnly": False
            }
            # 添加其他必要Cookie...
        ]
        
        await context.add_cookies(cookies)
        print("✅ 已设置Cookies:", await context.cookies())
        
        # 6. 导航到目标页面前确保Cookie已设置
        await page.evaluate("() => location.reload()")  # 刷新确保Cookie生效
        
        # 7. 导航到目标页面
        target_url = "https://xuntian-cloud-test3.tclpv.com/"
        print(f"🌐 正在访问: {target_url}")
        await page.goto(target_url, wait_until="networkidle", timeout=60000)
        
        # 8. 设置 sessionStorage（此时页面已加载，执行不会丢失）
        await page.evaluate(f"""
            () => {{
                sessionStorage.setItem('token', '{data['token']}');
                sessionStorage.setItem('refreshToken', '{data['refreshToken']}');
                sessionStorage.setItem('userId', '{data['userId']}');
                sessionStorage.setItem('admin_token', '{admin_token}');
                sessionStorage.setItem('admin_refresh_token', '{admin_refresh_token}');
            }}
        """)
        
        # 9. 验证Cookie是否被携带
        current_cookies = await context.cookies()
        print("\n🟢 当前页面Cookies:")
        for cookie in current_cookies:
            print(f"{cookie['name']}: {cookie['value']}")
        
        # 10. 检查登录状态
        try:
            await page.wait_for_selector(".user-info", timeout=10000)
            print("✅ 登录成功！")
            
            # 获取用户名验证
            user_name = await page.text_content(".user-info .name")
            print(f"👤 当前用户: {user_name}")
        except Exception as e:
            print(f"❌ 登录失败: {str(e)}")
            await page.screenshot(path="login_failure.png")
            print("🖼️ 已保存截图: login_failure.png")
            
            # 打印页面内容调试
            html = await page.content()
            print("📄 页面内容:", html[:500])
        
        # 保持浏览器打开
        print("\n🟢 按回车键退出...")
        input()

asyncio.run(main())